Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = "./traffic-signs-data/train.p"
testing_file = "./traffic-signs-data/test.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below.

In [2]:
import pandas as pd
### Replace each question mark with the appropriate value.

# TODO: Number of training examples
n_train = train['features'].shape[0]

# TODO: Number of testing examples.
n_test = test['features'].shape[0]

# TODO: What's the shape of an traffic sign image?
image_shape = train['features'][0].shape

# TODO: How many unique classes/labels there are in the dataset.
valCount = pd.Series(train['labels']).value_counts()
n_classes = len(valCount)
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 39209
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [3]:
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
import numpy as np
np.random.seed(0)
# Visualizations will be shown in the notebook.
%matplotlib inline
#Change default size of figures:
plt.rcParams["figure.figsize"] = (18,9)

arr = list(range(max(train['labels'])+1))


# Loop through the pictures to get an intuition for the example.
# This was as well used to build the name dictionary.
# next time I read till the end of the instruction to find the .csv file :D
xTrain, yTrain = shuffle(train['features'], train['labels'], random_state = 0)
f, axis = plt.subplots(nrows=4, ncols=11)

for i in range(len(xTrain)):
    if(len(arr)==0): 
        break
    if(yTrain[i] in arr):
        axis[yTrain[i]//11, yTrain[i]%11].set_title("%d" % yTrain[i])
        axis[yTrain[i]//11, yTrain[i]%11].imshow(xTrain[i])
        arr.remove(yTrain[i])
In [4]:
#Build a dictonary to get strings instead of numbers for the next plot
trafficSignDict = {
    0: "Speed Limit 20",
    1: "Speed Limit 30",
    2: "Speed Limit 50",
    3: "Speed Limit 40",
    4: "Speed Limit 70",
    5: "Speed Limit 80",
    6: "Lift Speed Limit 80",
    7: "Speed Limit 100",
    8: "Speed Limit 120",
    9: "Overtaking Forbidden",
    10: "Overtaking Forbidden Lorries",
    11: "Right Of Way Now",
    12: "Right Of Way Street",
    13: "Give Way",
    14: "Stop",
    15: "Drive-Through Forbidden",
    16: "Lorries Forbidden",
    17: "Entering Forbidden",
    18: "Attention",
    19: "Sharp Curve Left",
    20: "Sharp Curve Right",
    21: "Multiple Sharpe Curves",
    22: "Bumps",
    23: "Slippy Road",
    24: "Road Narrows",
    25: "Roadworks",
    26: "Traffic Light",
    27: "Pedestrians",
    28: "Children Playing",
    29: "Cyclists",
    30: "Frost",
    31: "Game Pass",
    32: "All Restrictions Lifted",
    33: "Go Right",
    34: "Go Left",
    35: "Go Straight",
    36: "Go Straight or Right",
    37: "Go Straight or Left",
    38: "Go Right Around Obstacle",
    39: "Go Left Around Obstacle",
    40: "Roundabout",
    41: "Overtaking allowed again",
    42: "Lorries are allowed to overtake again"
    }
In [5]:
arr = list(range(max(train['labels'])+1))
ticks = [trafficSignDict[i] for i in arr]
ticks.append('')
arr = np.array(arr) + .5
plt.hist(train['labels'], bins=np.arange(0,44, 1))
plt.xticks(arr, ticks, rotation=90)
Out[5]:
([<matplotlib.axis.XTick at 0x7fb4927a2748>,
  <matplotlib.axis.XTick at 0x7fb492c398d0>,
  <matplotlib.axis.XTick at 0x7fb492800a20>,
  <matplotlib.axis.XTick at 0x7fb498acc3c8>,
  <matplotlib.axis.XTick at 0x7fb498accdd8>,
  <matplotlib.axis.XTick at 0x7fb498ad0828>,
  <matplotlib.axis.XTick at 0x7fb498ad6278>,
  <matplotlib.axis.XTick at 0x7fb498ad6c88>,
  <matplotlib.axis.XTick at 0x7fb498a586d8>,
  <matplotlib.axis.XTick at 0x7fb498a5d128>,
  <matplotlib.axis.XTick at 0x7fb498a5db38>,
  <matplotlib.axis.XTick at 0x7fb498a5f588>,
  <matplotlib.axis.XTick at 0x7fb498a5ff98>,
  <matplotlib.axis.XTick at 0x7fb498a639e8>,
  <matplotlib.axis.XTick at 0x7fb498a69438>,
  <matplotlib.axis.XTick at 0x7fb498a69e48>,
  <matplotlib.axis.XTick at 0x7fb498a6b898>,
  <matplotlib.axis.XTick at 0x7fb498a702e8>,
  <matplotlib.axis.XTick at 0x7fb498a70cf8>,
  <matplotlib.axis.XTick at 0x7fb498a73748>,
  <matplotlib.axis.XTick at 0x7fb498a77198>,
  <matplotlib.axis.XTick at 0x7fb498a77ba8>,
  <matplotlib.axis.XTick at 0x7fb498a7c5f8>,
  <matplotlib.axis.XTick at 0x7fb498a7f048>,
  <matplotlib.axis.XTick at 0x7fb498a7fa58>,
  <matplotlib.axis.XTick at 0x7fb498a854a8>,
  <matplotlib.axis.XTick at 0x7fb498a85eb8>,
  <matplotlib.axis.XTick at 0x7fb498a88908>,
  <matplotlib.axis.XTick at 0x7fb498a8b358>,
  <matplotlib.axis.XTick at 0x7fb498a8bd68>,
  <matplotlib.axis.XTick at 0x7fb498a927b8>,
  <matplotlib.axis.XTick at 0x7fb498a94208>,
  <matplotlib.axis.XTick at 0x7fb498a94c18>,
  <matplotlib.axis.XTick at 0x7fb498a19668>,
  <matplotlib.axis.XTick at 0x7fb498a1d0b8>,
  <matplotlib.axis.XTick at 0x7fb498a1dac8>,
  <matplotlib.axis.XTick at 0x7fb498a20518>,
  <matplotlib.axis.XTick at 0x7fb498a20f28>,
  <matplotlib.axis.XTick at 0x7fb498a26978>,
  <matplotlib.axis.XTick at 0x7fb498a283c8>,
  <matplotlib.axis.XTick at 0x7fb498a28dd8>,
  <matplotlib.axis.XTick at 0x7fb498a2c828>,
  <matplotlib.axis.XTick at 0x7fb498a31278>],
 <a list of 43 Text xticklabel objects>)

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [6]:
from sklearn.model_selection import train_test_split
import cv2
### Preprocess the data here.
### Feel free to use as many code cells as needed.
#Check min and max before processing (should be 0,255)

def minValImage(arr, channel = 0):
    return np.min(np.min(np.min(arr[:,:,:,channel], axis=1),axis=1),axis=0)

def maxValImage(arr, channel = 0):
    return np.max(np.max(np.max(arr[:,:,:,channel], axis=0),axis=0),axis=0)

def addGreyLayer(arr):
    return np.concatenate((arr, [cv2.cvtColor(data, cv2.COLOR_RGB2GRAY).reshape((32,32,1)) for data in arr]), axis=3)

def applyNormalisation(arr):
    return np.array([2.*(arr[:,:] - np.min(np.min(arr,axis=0), axis=0))[:,:]/
          (np.max(np.max(arr,axis=0), axis=0)-np.min(np.min(arr,axis=0), axis=0)) -1 for arr in arr])

def preprocessImages(arr):
    arr = addGreyLayer(arr)
    arr = applyNormalisation(arr)
    return arr
    
    
xTest = test['features']
yTest = test['labels']
print("Train Red Min %g Max: %g" % (minValImage(xTrain), maxValImage(xTrain)))
print("Test Red Min: %g Max: %g" % (minValImage(xTest), maxValImage(xTest)))
xTrain = preprocessImages(xTrain)
xTest = preprocessImages(xTest)
Train Red Min 0 Max: 255
Test Red Min: 0 Max: 255

Question 1

Describe how you preprocessed the data. Why did you choose that technique?

Answer: A greyscale layer is added as a fourth channel to all pictures to provide an easier edge detection.

In addition, the data were normalised to provide a mean of 0 and a deviation of 1. This provides the network with an easy to handle representation of the data

In [7]:
def shiftImg(arr, horizontal, vertical):
    arr = arr.copy()
    if(horizontal>0):arr = np.concatenate((arr[horizontal:,:],np.zeros((horizontal,arr.shape[1],arr.shape[2]))), axis=0)
    elif(horizontal<0):arr = np.concatenate((np.zeros((np.abs(horizontal),arr.shape[1],arr.shape[2])), arr[:horizontal,:]), axis=0)
    if(vertical>0):arr = np.concatenate((arr[:,vertical:],np.zeros((arr.shape[0],vertical,arr.shape[2]))), axis=1)
    elif(vertical<0):arr = np.concatenate((np.zeros((arr.shape[0], np.abs(vertical),arr.shape[2])), arr[:,:vertical]), axis=1)
    return arr

def shiftImages(arr):
    randomJumps = np.random.randint(-2,2+1, (len(arr),2)) # determine shifts of the pictures randomly
    shiftedArr = [shiftImg(arr[i], randomJumps[i][0], randomJumps[i][1]) for i in range(len(arr))] #shifting the pictures
    return shiftedArr
def minimiseImages(arr):
    smallerImgs = np.zeros(arr.shape)
    for i in range(len(arr)):
        smallerImgs[i][3:-3,3:-3] = cv2.resize(arr[i], (26,26)) #shifting the pictures
    return smallerImgs

shiftedImgs = shiftImages(xTrain)
smallerImgs = minimiseImages(xTrain)
xTrain = np.concatenate((xTrain, shiftedImgs, smallerImgs) , axis=0)
yTrain = np.concatenate((yTrain, yTrain, yTrain), axis=0)
xTrain, xValidation, yTrain, yValidation = train_test_split(xTrain, yTrain, random_state = 42)
In [8]:
#Check min and max after processing (should by -1,1)
print("Train Min: %g Max: %g" % (minValImage(xTrain), maxValImage(xTrain)))
print("Train Min: %g Max: %g" % (minValImage(xValidation), maxValImage(xValidation)))
print("Test Min: %g Max: %g" % (minValImage(xTest), maxValImage(xTest)))

# Look at some sample images to make sure nothing went wrong.
# Don't look at the colour as the values are right but matplotlib 
# does not like value between -1 and 1
indices = np.random.randint(0,len(xTrain), 10)
f, axis = plt.subplots(nrows=2, ncols=5)
for i in range(len(indices)):
        axis[i//5, i%5].set_title("Train %d" % indices[i])
        axis[i//5, i%5].imshow(xTrain[indices[i]][:,:,:3])
Train Min: -1 Max: 1
Train Min: -1 Max: 1
Test Min: -1 Max: 1
In [9]:
#Look at the test set as well
indices = np.random.randint(0,len(xTest), 10)
f, axis = plt.subplots(nrows=2, ncols=5)
for i in range(len(indices)):
        axis[i//5, i%5].set_title("Test %d" % indices[i])
        axis[i//5, i%5].imshow(xTrain[indices[i]][:,:,:3])

Question 2

Describe how you set up the training, validation and testing data for your model. Optional: If you generated additional data, how did you generate the data? Why did you generate the data? What are the differences in the new dataset (with generated data) from the original dataset?

Answer: The pictures were augmented by applying a random shift of the original pictures as well as making some of them smaller. Afterwards, the data were split into train and validation using the train_test_split from sklearn, a tested and validated function to provide random train set splits.

In [10]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

'''
Created on 30 Jan 2017

@author: Jendrik
'''

import tensorflow as tf
import numpy as np

class CNN(object):
    """
        A class to easily build a convolutional neural network with 2 convolutional layers and 
        three fully connected ones.
    """
    

    def __init__(self, shapeOfInput, numberOfOutputs, layers):
        """
            The constructor for the CNN
            
            Variables:
                shapeOfInput - the shape of the input data
                numberOfOutputs - the number of outputs the network shall provide
                convKind - the kind of convolution, which shall be used
        """
        self.weights = {}
        self.biases = {}
        self.x = tf.placeholder(tf.float32, shape=[None, shapeOfInput[0], shapeOfInput[1], shapeOfInput[2]], name='x')
        self.keepProb = tf.placeholder(tf.float32, name='keepProb')
        # Build a weight variable for the convolution
        # in this case every 5x5 patch from the sound is taken
        # and converted in to 32 output channels
        
        lenOut = 16
        # Build a bias for the convolution to keep all relus active at the beginning
        
        # reshape x to a four dimensional tensor
        # First dimension all the sounds
        # second frequency and third dimension time
        hPool=None
        outs=[]
        assert(lenOut*2%4 == 0)
        for i in range(len(layers)):
            bConv = self.biasVariable([lenOut*2], name='bConv%g'%i)
            self.biases.update({'bConv%g'%i:bConv})
            if(layers[i] == '5x5'):
                if(hPool==None):
                    wConv1 = self.weightVariable([5,5, shapeOfInput[2], lenOut*2], name='wConv%g'%i)
                    self.weights.update({'wConv%g'%i:wConv1})
                    hConv = self.conv2D(self.x, wConv1, 'VALID') + bConv
                else: 
                    wConv1 = self.weightVariable([5,5, lenOut, lenOut*2], name='wConv%g'%i)
                    self.weights.update({'wConv%g'%i:wConv1})
                    hConv = self.conv2D(hPool, wConv1, 'VALID') + bConv
                hConv = tf.nn.relu(hConv, name='hConv%g'%i)
                hPool = tf.nn.max_pool(hConv, ksize=[1,3,3,1], strides=[1,3,3,1], padding='VALID', name='hPool%g'%i)
                lenOut*=2
            elif(layers[i] == 'inception'):
                weights=[]
                weights.append(self.weightVariable([1,1, lenOut, lenOut*2//4], name='wConvPre5x5%g'%i))
                weights.append(self.weightVariable([5,5, lenOut*2//4, lenOut*2//4], name='wConv5x5%g'%i))
                weights.append(self.weightVariable([1,1, lenOut, lenOut*2//4], name='wConvPre3x3%g'%i))
                weights.append(self.weightVariable([3,3, lenOut*2//4, lenOut*2//4], name='wConv3x3%g'%i))
                weights.append(self.weightVariable([1,1, lenOut, lenOut*2//4], name='wConv1x1%g'%i))
                weights.append(self.weightVariable([1,1, lenOut, lenOut*2//4], name='wConvavgPool%g'%i))
                weights.append(self.weightVariable([1,1, lenOut, lenOut*2//4], name='wConvPastAvg%g'%i))
                biases = []
                biases.append(self.biasVariable([lenOut*2//4], name='bConvInner5x5%g'%i))
                biases.append(self.biasVariable([lenOut*2//4], name='bConvInner3x3%g'%i))
                self.weights.update({'wConv%g'%i:weights})
                hConv = self.inception(hPool, weights, biases) + bConv
                hPool = tf.nn.relu(hConv, name='hConv%g'%i)
                lenOut*=2
                outs.append(hPool)
        
        neurons = []
        for pool in outs:
            numberOfNeurons = int(pool.get_shape()[1]*pool.get_shape()[2]*pool.get_shape()[3])
            neurons.append(tf.reshape(pool, [-1, numberOfNeurons]))
        hPoolEnd = tf.concat(1, neurons)
        wFC1 = self.weightVariable([int(hPoolEnd.get_shape()[1]), 1024], name='wFC1')
        bFC1 = self.biasVariable([1024], name='bFC1')
        self.weights.update({'wFC1':wFC1})
        self.biases.update({'bFC1':bFC1})
        hFC1 = tf.nn.relu(tf.matmul(hPoolEnd, wFC1) + bFC1, name='hFC1')
        
        hFC1Drop = tf.nn.dropout(hFC1, self.keepProb)
        # Build the readout layer:
        wFC3 = self.weightVariable([1024, numberOfOutputs], name='wFC3')
        bFC3 = self.biasVariable([numberOfOutputs], name='bFC3')
        self.weights.update({'wFC3':wFC3})
        self.biases.update({'bFC3':bFC3})
        self.out = tf.matmul(hFC1Drop, wFC3) + bFC3
        
    
    def weightVariable(self, shape, name=''):
        """
            Builds a weight variable with the given shape
        """
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial, name=name)

    def biasVariable(self, shape, name=''):
        """
            Builds a bais variable with the given shape
        """
        initial = tf.constant(0.1, shape = shape)
        return tf.Variable(initial, name=name)
    
    def inception(self,x,weights,biases):
        conv5x5 = self.conv2D(self.conv2D(x, weights[0]), weights[1]) + biases[0]
        conv3x3 = self.conv2D(self.conv2D(x, weights[2]), weights[3]) + biases[1]
        conv = tf.nn.relu(self.conv2D(x, weights[4]))
        avg = tf.nn.avg_pool(x, ksize=[1,3,3,1], strides= [1,1,1,1], padding='SAME') 
        avgConv = self.conv2D(avg, weights[5])
        out = tf.concat(3, [conv5x5, conv3x3, conv, avgConv])
        return out 
    
    def conv2D(self, x, W, padding='SAME'):
        return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding=padding)

    def maxPool2X2(self, x, name):
        return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID', name=name)
        
    def encodeIndices(self, indices):
        """
            convert indices to one-hot-encoded vectors
            Variables:
                indices - the indices which shall be one-hot encoded
        """
        yBatch = np.zeros((len(indices), self.out.get_shape()[1]))
        for i in range(len(yBatch)):
            yBatch[i, indices[i]] = 1
        return yBatch
    
    def labelData(self, sess, x, trainer):
        labelsArr = np.zeros((len(x)))
        for i in range(len(x)//trainer.batchSize + 1):
            xBatch = trainer.buildSubBatch(i, x)
            labelsArr[i*trainer.batchSize:(i+1)*trainer.batchSize] = tf.argmax(tf.nn.softmax(self.out), 1).eval(feed_dict={self.x:xBatch, self.keepProb: 1.0}, session=sess)
        return labelsArr
    
    def topK(self, sess, x, trainer, numberOfK=5):
        topK = np.zeros((len(x),2,5))
        for i in range(len(x)//trainer.batchSize + 1):
            xBatch = trainer.buildSubBatch(i, x)
            res = sess.run(tf.nn.top_k(tf.nn.softmax(self.out), numberOfK),feed_dict={self.x:xBatch, self.keepProb: 1.0})
            topK[i*trainer.batchSize:(i+1)*trainer.batchSize,0,:] = res[0]
            topK[i*trainer.batchSize:(i+1)*trainer.batchSize,1,:] = res[1]
        return topK
In [11]:
cnn = CNN(xTrain[0].shape, 43, ['5x5','inception', '5x5', 'inception'])

Question 3

What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.

Answer: The model is a 4 layer convolutional network. The first layer is a 5x5 convolution followed by a 3x3 max pooling. The second layer is an inception layer, combining 1x1, 1x1+3x3, 1x1+5x5 and avgPool+1x1 convolutions. The third layer is similar to the first one and the fourth similar to the second. Hereby, the output from every inception layer is fed to a fully connected layer with a width of 1024. This is then connected to the outputlayer with the size of the classes.

In [12]:
class Trainer(object):
    
    
    def __init__(self, network,learningRate, globalStep, batchSize=128):
        self.network = network
        self.y_ = tf.placeholder(tf.float32, shape=[None, network.out.get_shape()[1]])
        self.batchSize = batchSize
        self.crossEntropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(network.out, self.y_))
        self.optimizer = tf.train.AdamOptimizer(learningRate)
        self.trainStep = self.optimizer.minimize(self.crossEntropy, global_step=globalStep)
        correctPrediction = tf.equal(tf.argmax(tf.nn.softmax(network.out), 1), tf.argmax(self.y_, 1))
        self.accuracy = tf.reduce_mean(tf.cast(correctPrediction, tf.float32))
        self.saver = tf.train.Saver()
        with tf.name_scope('summaries'):
            tf.summary.scalar('trainAccuracy', self.accuracy)
            
    def buildSubBatch(self, i ,x, y=None):
        if(y==None):
            return x[i*self.batchSize:(i+1)*self.batchSize,:,:,:]
        if (i+1)*self.batchSize < len(x)+1:
            if(len(y.shape) == 1):
                yBatch = self.network.encodeIndices(y[i*self.batchSize:(i+1)*self.batchSize])
                return x[i*self.batchSize:(i+1)*self.batchSize,:,:,:], yBatch
            else:
                xBatch = x[i*self.batchSize:(i+1)*self.batchSize,:,:,:]
                yBatch = y[i*self.batchSize:(i+1)*self.batchSize,:]
                return xBatch, yBatch
        else:
            if(len(y.shape) == 1):
                yBatch = self.network.encodeIndices(y[i*self.batchSize:(i+1)*self.batchSize])
                return x[i*self.batchSize:,:,:,:], yBatch
            else:
                xBatch = x[i*self.batchSize:(i+1)*self.batchSize,:,:,:]
                yBatch = y[i*self.batchSize:(i+1)*self.batchSize,:]
                return xBatch, yBatch
    
    def testAccuracy(self, sess, x, y):
        testAccuracy = 0
        for i in range(len(x)//self.batchSize):
            xBatch, yBatch = self.buildSubBatch(i, x, y)
            testAccuracy += len(xBatch)*self.accuracy.eval(feed_dict={
                self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: 1.0}, session=sess)
        if((len(x)%self.batchSize)!=0):
            xBatch, yBatch = self.buildSubBatch(len(x)//self.batchSize, x, y)
            testAccuracy += len(xBatch)*self.accuracy.eval(feed_dict={
                self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: 1.0}, session=sess)
        return testAccuracy/len(x)
    
    def stochasticTestAccuracy(self, sess, x, y, subBatchSize=1024):
        testAccuracy = 0
        indices = np.random.randint(0, len(x), subBatchSize)
        xTestBatch = x[indices,:,:,:]
        yTestBatch = y[indices]
        for i in range(subBatchSize//self.batchSize):
            xBatch, yBatch = self.buildSubBatch(i, xTestBatch, yTestBatch)
            testAccuracy += len(xBatch)*self.accuracy.eval(feed_dict={
                self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: 1.0}, session=sess)
        if((subBatchSize%self.batchSize)!=0):
            xBatch, yBatch = self.buildSubBatch(len(xTestBatch)//self.batchSize, xTestBatch, yTestBatch)
            testAccuracy += len(xBatch)*self.accuracy.eval(feed_dict={
                self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: 1.0}, session=sess)
        return testAccuracy/len(indices)
    
    def train(self, sess, xTrain, yTrain, keepProb):
        """
            Performs a training step of the network going through the full 
            dataset provided
            Variables:
                sess - the session in which the execution shall be performed
                xTrain - contextData
                yTrain - labels
        """
        for i in range(len(xTrain)//self.batchSize):
            xBatch, yBatch = self.buildSubBatch(i, xTrain, yTrain)
            self.trainStep.run(feed_dict={
                    self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: keepProb}, session=sess)
        if((len(xTrainBatch)%self.batchSize)!=0):
            xBatch, yBatch = self.buildSubBatch(i, xTrain, yTrain)
            self.trainStep.run(feed_dict={
                    self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: keepProb}, session=sess)
        #print("Train Accuracy %g" % self.testAccuracy(sess, xTrain, yTrain))
            
    def stochasticTrain(self, sess, xTrain, yTrain, keepProb, subBatchSize = 1024):
        """
            Performs a training step of the network going through 
            a stochastically selected sub batch of the 
            dataset provided
            Variables:
                sess - the session in which the execution shall be performed
                xTrain - contextData
                yTrain - labels
                subBatchSize - the size of the batch selected for stochastic training
        """
        indices = np.random.randint(0, len(xTrain), subBatchSize)
        xTrainBatch = xTrain[indices,:,:,:]
        yTrainBatch = yTrain[indices]
        for i in range(subBatchSize//self.batchSize):
            xBatch, yBatch = self.buildSubBatch(i, xTrainBatch, yTrainBatch)
            self.trainStep.run(feed_dict={
                    self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: keepProb}, session=sess)
        if((subBatchSize%self.batchSize)!=0):
            xBatch, yBatch = self.buildSubBatch(len(xTrainBatch)//self.batchSize, xTrainBatch, yTrainBatch)
            self.trainStep.run(feed_dict={
                    self.network.x:xBatch, self.y_:yBatch, self.network.keepProb: keepProb}, session=sess)
In [13]:
### Train your model here.
### Feel free to use as many code cells as needed.
sess = tf.Session(config=tf.ConfigProto(
            allow_soft_placement=True,
            log_device_placement=True))

globalStep=tf.Variable(0, trainable=False)
minVal = tf.Variable(1e-4, trainable=False)
learningRate = tf.reduce_max([minVal, tf.train.exponential_decay(1e-3, globalStep,
                                           200, 0.5, staircase=True)], axis=0)
#learningRate = tf.train.piecewise_constant(globalStep, boundaries, values)
trainer = Trainer(cnn, learningRate, globalStep, 1024)
merged = tf.summary.merge_all()
 
# Create a saver for writing training checkpoints.

summaryWriter = tf.summary.FileWriter('./tmp/log', sess.graph)
sess.run(tf.global_variables_initializer())
In [14]:
#Run this cell if you want to restore the variables from a checkpoint file
try:
    trainer.saver.restore(sess, './cnn.ckpt')
    print("Model Restored")
except:
    print("Restoring Failed")
    pass
Restoring Failed
In [15]:
#Run this cell to train the model
lastValAcc = trainer.testAccuracy(sess, xValidation, yValidation)
killArg = 0
i=0
import time
trainer.stochasticTrain(sess, xTrain, yTrain, .3)
print("Len xValidation: %g Percentage for a change:%.2f" %(len(xValidation), 100.*30./len(xValidation)))
start_time = time.time()
while(killArg!=20):
    trainer.stochasticTrain(sess, xTrain, yTrain, .3)
    if(i%10 == 0):
        valAcc = trainer.testAccuracy(sess, xValidation, yValidation)
        # If not more than 30 values are correctly predicted in addition
        # it is not considered better
        if((lastValAcc - valAcc) >-30./len(xValidation)): killArg += 1
        else:
            if(valAcc>0.97):
                print("Write Checkpoint valAcc:%g"%(valAcc))
                trainer.saver.save(sess, './cnn.ckpt')
            lastValAcc = valAcc
            killArg = 0
        if(i%50==0):
            print("Train Time: %s seconds" % (time.time() - start_time))
            print("Epoch:%g Train Accuracy:%g Validation Accuracy: %g" % (i, 
                trainer.stochasticTestAccuracy(sess, xTrain, yTrain, 10240),
                trainer.testAccuracy(sess, xValidation, yValidation)))
            start_time = time.time()
    i+=1
/home/jjordening/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:18: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
Len xValidation: 29407 Percentage for a change:0.10
Train Time: 2.5328357219696045 seconds
Epoch:0 Train Accuracy:0.0814453 Validation Accuracy: 0.0819873
Train Time: 27.55963373184204 seconds
Epoch:50 Train Accuracy:0.491699 Validation Accuracy: 0.47958
Train Time: 26.229421138763428 seconds
Epoch:100 Train Accuracy:0.725781 Validation Accuracy: 0.712721
Train Time: 26.24162721633911 seconds
Epoch:150 Train Accuracy:0.836426 Validation Accuracy: 0.82613
Train Time: 26.228856325149536 seconds
Epoch:200 Train Accuracy:0.90752 Validation Accuracy: 0.903458
Train Time: 26.219569206237793 seconds
Epoch:250 Train Accuracy:0.927148 Validation Accuracy: 0.920699
Train Time: 26.214540481567383 seconds
Epoch:300 Train Accuracy:0.944629 Validation Accuracy: 0.936002
Train Time: 26.21649670600891 seconds
Epoch:350 Train Accuracy:0.952734 Validation Accuracy: 0.947802
Train Time: 26.221030712127686 seconds
Epoch:400 Train Accuracy:0.965723 Validation Accuracy: 0.957663
Train Time: 26.215617656707764 seconds
Epoch:450 Train Accuracy:0.97041 Validation Accuracy: 0.963002
Train Time: 26.26048517227173 seconds
Epoch:500 Train Accuracy:0.975098 Validation Accuracy: 0.967661
Train Time: 26.25631809234619 seconds
Epoch:550 Train Accuracy:0.976562 Validation Accuracy: 0.968409
Write Checkpoint valAcc:0.971367
Train Time: 27.109617233276367 seconds
Epoch:600 Train Accuracy:0.979004 Validation Accuracy: 0.970313
Write Checkpoint valAcc:0.973034
Train Time: 27.193413257598877 seconds
Epoch:650 Train Accuracy:0.981934 Validation Accuracy: 0.97317
Write Checkpoint valAcc:0.974938
Train Time: 27.119840145111084 seconds
Epoch:700 Train Accuracy:0.981445 Validation Accuracy: 0.973578
Train Time: 26.254717350006104 seconds
Epoch:750 Train Accuracy:0.98252 Validation Accuracy: 0.975006
Write Checkpoint valAcc:0.976128
Train Time: 27.202306270599365 seconds
Epoch:800 Train Accuracy:0.983008 Validation Accuracy: 0.97589
Train Time: 26.251796007156372 seconds
Epoch:850 Train Accuracy:0.985352 Validation Accuracy: 0.976638
Write Checkpoint valAcc:0.977318
Train Time: 27.208406448364258 seconds
Epoch:900 Train Accuracy:0.984863 Validation Accuracy: 0.977284
Train Time: 26.268988847732544 seconds
Epoch:950 Train Accuracy:0.988672 Validation Accuracy: 0.977522
Train Time: 26.272931575775146 seconds
Epoch:1000 Train Accuracy:0.986133 Validation Accuracy: 0.978134
Write Checkpoint valAcc:0.978917
Train Time: 27.076809644699097 seconds
Epoch:1050 Train Accuracy:0.984961 Validation Accuracy: 0.978202
Train Time: 26.22520661354065 seconds
Epoch:1100 Train Accuracy:0.98584 Validation Accuracy: 0.978849
Write Checkpoint valAcc:0.980107
Train Time: 27.18191146850586 seconds
Epoch:1150 Train Accuracy:0.989844 Validation Accuracy: 0.980345
Train Time: 26.281894207000732 seconds
Epoch:1200 Train Accuracy:0.989062 Validation Accuracy: 0.980209
Write Checkpoint valAcc:0.981229
Train Time: 27.24714159965515 seconds
Epoch:1250 Train Accuracy:0.989258 Validation Accuracy: 0.981127
Train Time: 26.532273054122925 seconds
Epoch:1300 Train Accuracy:0.989648 Validation Accuracy: 0.981569
Write Checkpoint valAcc:0.982555
Train Time: 27.227057933807373 seconds
Epoch:1350 Train Accuracy:0.990527 Validation Accuracy: 0.981909
Train Time: 26.27134418487549 seconds
Epoch:1400 Train Accuracy:0.992383 Validation Accuracy: 0.982759
Train Time: 26.272161960601807 seconds
Epoch:1450 Train Accuracy:0.990332 Validation Accuracy: 0.982691
Write Checkpoint valAcc:0.983881
Train Time: 27.131360292434692 seconds
Epoch:1500 Train Accuracy:0.991699 Validation Accuracy: 0.983881
Train Time: 26.257018089294434 seconds
Epoch:1550 Train Accuracy:0.991797 Validation Accuracy: 0.983813
Train Time: 26.25977396965027 seconds
Epoch:1600 Train Accuracy:0.99209 Validation Accuracy: 0.983813
Train Time: 26.269189596176147 seconds
Epoch:1650 Train Accuracy:0.993457 Validation Accuracy: 0.984834
Write Checkpoint valAcc:0.985038
Train Time: 27.233052968978882 seconds
Epoch:1700 Train Accuracy:0.991797 Validation Accuracy: 0.984766
Train Time: 26.268968105316162 seconds
Epoch:1750 Train Accuracy:0.993262 Validation Accuracy: 0.985106
Train Time: 26.277623414993286 seconds
Epoch:1800 Train Accuracy:0.99375 Validation Accuracy: 0.985276
Train Time: 26.281097173690796 seconds
Epoch:1850 Train Accuracy:0.994043 Validation Accuracy: 0.985718
In [16]:
trainer.saver.restore(sess, './cnn.ckpt')
labels = cnn.labelData(sess, xValidation, trainer)
wrongIndices = []
for i in range(len(labels)):
    if(labels[i] != yValidation[i]): wrongIndices.append(i)
print(1.*len(wrongIndices)/len(labels))

f, axis = plt.subplots(nrows=4, ncols=11)

for i in range(min([len(wrongIndices), 44])):
    imageIndex = wrongIndices[i]
    axis[i//11, i%11].set_title("%d,sayed:%d" % (yValidation[imageIndex], labels[imageIndex]))
    axis[i//11, i%11].imshow(xValidation[imageIndex][:,:,:3])


print("Step:%g Test Accuracy %g" % (globalStep.eval(session = sess), trainer.testAccuracy(sess, xTest, yTest)))
0.014962423912673854
/home/jjordening/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:18: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
Step:1662 Test Accuracy 0.95099

Question 4

How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)

Answer: The model was trained using the Adam optimizer with an exponentially decaying learning rate, starting at 1e-3 and decaying to 1e-4, by halfing every 200 steps. Hereby every training step was stochastic using a batchs of 1024 sample. Every 10 training steps the accuracy against the validation set is checked. If the not more than 30 examples in the validation set are evaluated correctly in addtion to the ones at the last checkpoint within 200 steps the training is aborted.

Question 5

What approach did you take in coming up with a solution to this problem? It may have been a process of trial and error, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think this is suitable for the current problem.

Answer: I started by normalising the data to a mean of 0 and a maxdev of 1. Then I implemented a simple convolutional network with two convolutional layers and a fully connected layer with 1024 neurons to get a baseline value for the accuracy, beign 86,3%. Afterwards, I implemented a small version of the Google LeNet using a convolutional input layers (with 'VALID' padding to save some computations later) and then a inception layer, a convolutional layer and again an inception layer. Each inception layer outputs its infos to the final layer which is fully connected layer with a width of 1024. Then, the incorrectly classified examples of the validation set were investigated. After investigating the bad classified pictures, I decided to add a greyscale channel to the image to provide a guidline for better edge detection. Furthermore, I decided to renormalise the data to have a mean of 0 and a dev of 1. This increases the contrast of the pictures and makes classification easier, especially for dark pictures. Furthermore, I added an augmented version of the pictures showing the signs smaller, as smaller signs appeared often in the incorrectly classified pictures. During all those these steps the learning rate behaviour was adapted from time to time to provide better convergence behaviour to the model.


Step 3: Test a Model on New Images

Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [20]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
import matplotlib.image as mpimage
folderPath = "testImages/snippets"
paths=['11.png', '7.png','2.png', '5.png', '9.png']
#paths = os.listdir(folderPath)
numberOfPics = len(paths)
pictures = []
for path in paths:
    if(path.endswith('.png')):
        img = mpimage.imread(folderPath+"/"+path)
        if(img.shape[2] == 4):
            img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
        img = cv2.resize(img, (32,32))
        pictures.append(img)

Question 6

Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It could be helpful to plot the images in the notebook.

Answer: The following 5 images were choosen. They are hard to classify as they have either stickers on them (picture 1-3, a typical problem in Hamburg downtown :D) or because they are tilted strongly (picture 4) or a sign which is similar but not the same as the ones in the training set (picture 5)

In [21]:
### Run the predictions here.
### Feel free to use as many code cells as needed.
processPics = preprocessImages(pictures)
labels = cnn.labelData(sess, processPics, trainer)
numberOfPics += numberOfPics%2

f, ax = plt.subplots(nrows = 2, ncols = numberOfPics//2)
for i in range(len(paths)):
    ax[i//(numberOfPics//2),i%(numberOfPics//2)].set_title(trafficSignDict.get(labels[i]))
    ax[i//(numberOfPics//2),i%(numberOfPics//2)].imshow(pictures[i])

Question 7

Is your model able to perform equally well on captured pictures when compared to testing on the dataset? The simplest way to do this check the accuracy of the predictions. For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate.

NOTE: You could check the accuracy manually by using signnames.csv (same directory). This file has a mapping from the class id (0-42) to the corresponding sign name. So, you could take the class id the model outputs, lookup the name in signnames.csv and see if it matches the sign from the image.

Answer: The model is not as good as classifying the newly taken pictures compared to the ones in the test set. This originates in the fact, that I took quite uncommon examples of street signs when compared to the overall street sign occurence in Germany. However the algorithm seems to be quite robust against some distortions. Depending on the training cycle I had some different missclasifcations of the pictures.

Picture 1: Was sometimes classified correctly, but 1 time as well as a 70 speed limit sign. This could originate from the stickers adding white spaces to the sign. I would have expected a drive-through forbidden as well, but it did not occur till now.

Picture 2: Was always classified correctly, as the stickers doesn't change the overall look-alike of the picture.

Picture 3: Changed depending on the training circumstances. One time it was classified as go right around this obstacle, as the sticker in the middle makes it porbable to see an arrow pointing down to the right.

Picture 4: Was always classified correctly, so tilting does not seem that much of a problem.

Picture 5: Was mostly classified as 30 speed limit sign. Which is not that far away from the truth taking into account that the sign wasn't at all in the trianing set. Furthermore, a 30 sign is more likely to appear as the 20 sign is quite rare in the training distribution. Therefore, the algorithm seems to tend towards 30 signs. In addition it was one time classified as a stop sign which seems interesting.

In [22]:
### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.
topK = cnn.topK(sess, processPics, trainer, 5)
f, ax = plt.subplots(nrows = 3, ncols = numberOfPics//3)
for i in range(len(paths)):
    print("Picture: %g" % i, "Values:", topK[i,0], [trafficSignDict.get(number) for number in topK[i,1]])
    ax[i//(numberOfPics//3),i%(numberOfPics//3)].set_title(i)
    ax[i//(numberOfPics//3),i%(numberOfPics//3)].imshow(pictures[i])
Picture: 0 Values: [  9.99193490e-01   3.08065675e-04   1.76471498e-04   1.27875712e-04
   7.74893415e-05] ['Entering Forbidden', 'Speed Limit 70', 'Drive-Through Forbidden', 'Speed Limit 120', 'Stop']
Picture: 1 Values: [  9.95826542e-01   3.44269234e-03   4.51308704e-04   1.63099859e-04
   7.57535599e-05] ['Go Straight or Left', 'Go Left Around Obstacle', 'Go Right', 'Go Straight', 'Roundabout']
Picture: 2 Values: [ 0.83915526  0.14511912  0.00974428  0.00299685  0.00147317] ['Go Left', 'Go Right Around Obstacle', 'Roundabout', 'Go Straight or Left', 'Go Straight or Right']
Picture: 3 Values: [  1.00000000e+00   1.13338852e-11   1.10019112e-11   1.01158860e-12
   4.00584839e-13] ['Give Way', 'Drive-Through Forbidden', 'Right Of Way Street', 'Speed Limit 30', 'Speed Limit 50']
Picture: 4 Values: [  9.09073234e-01   8.65337998e-02   3.91741097e-03   2.88381474e-04
   1.05043597e-04] ['Speed Limit 30', 'Speed Limit 50', 'Speed Limit 20', 'Speed Limit 120', 'Speed Limit 100']

Question 8

Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

Answer: It can be seen, that the correct sign apperas always in the top 5. Actually even in the top 2. This even holds for picture 5, which is a sign which is only similar to the training data. What can be seen as well is, that the model is extremly certain, when it comes to the "give way"-sign. This seems reasonable, as it has a quite unique shape and is therefore easy to classify. This is completly different from picture 2, where the sticker on the sign gives rice to a head to head race between "go left" and "go right around this obstacle" as the sticker gives rise to the assumption of an arrow going from the top left to the bottom right.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In [ ]: